package com.test.spring.service.impl;

import com.test.spring.data.User;
import com.test.spring.repository.UserMapper;
import com.test.spring.service.UserService;
import com.test.spring.util.aspect.datasource.DataSource;
import com.test.spring.util.config.ThreadPoolExecutorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * Created by ll on 2017/4/4.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceTestImpl userTest;
    @Autowired
    private ThreadPoolExecutorConfig executorConfig;

    @DataSource(value = "masterDataSource")
    @Override
    public List<User> findMaster() {
        return userMapper.findAll();
    }

    @DataSource(value = "slaveDataSource")
    @Override
    public List<User> findSlave() {
        ExecutorService e = executorConfig.threadPoolTaskExecutor();
        Future<List<User>> future = e.submit(new Callable<List<User>>() {
            @Override
            public List<User> call() throws Exception {
                return userMapper.findAll();
            }
        });
        try {
            return future.get();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        } catch (ExecutionException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void test() throws Exception {
        int i =  testA();
        System.out.println("===================testA=====================");
        userTest.testB(i);
        System.out.println("===================testA=====================");
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = RuntimeException.class)
    @DataSource(value = "masterDataSource")
    public int testA() {
        User user = new User();
        user.setUserName("testA");
        userMapper.insertSelective(user);
        //返回插入后数据库主键id
        int id = user.getId();
        return id;
    }
}
